package com.sibu.yx.promotion.web.support.filter;


import com.doubo.common.util.StringUtil;
import com.doubo.json.util.JsonUtil;
import com.sibu.yx.promotion.common.constants.AppConstants;
import com.sibu.yx.promotion.common.enums.ErrorCodeEnum;
import com.sibu.yx.promotion.common.manage.ResponseManage;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import java.io.PrintWriter;

/*
 * @description: 拦截head中的token提交参数
 * @param:
 * @return:
 * @author: yuwenbo@wljs.com
 * @date:2020-06-06
 * @time:10:47
 **/
public class HeadTokenAuthenticationFilter extends AccessControlFilter {

    /**
     * 验证是否有登陆信息
     *
     * @param servletRequest
     * @param servletResponse
     * @param o
     * @return
     * @throws Exception 直接调用登陆token
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader(AppConstants.HEAD_TOKEN);
//        String uid = request.getHeader(AppConstants.HEAD_UID);
        if (StringUtil.isNull(token)) {
            return false;
        }
        UidToken tokenUidSubject = new UidToken();
        tokenUidSubject.setToken(token);
//        tokenUidSubject.setUid(uid);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(tokenUidSubject);
        } catch (Exception ex) {
            if (ex instanceof AuthenticationException) {
                servletResponse.setContentType("application/json;charset=UTF-8");
                servletResponse.setCharacterEncoding("utf-8");
                PrintWriter writer = servletResponse.getWriter();
                writer.write(JsonUtil.toJson(ResponseManage.fail(ErrorCodeEnum.SESSION_TIMEOUT.getErrorCode(), ex.getMessage())));
                writer.flush();
                writer.close();
                return false;
            }

        }

        if (subject.isAuthenticated()) {
            return true;
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        servletResponse.setContentType("application/json;charset=UTF-8");
        servletResponse.setCharacterEncoding("utf-8");
        servletResponse.getWriter().write(JsonUtil.toJson(ResponseManage.fail(ErrorCodeEnum.SESSION_TIMEOUT)));
        return false;
    }


}
